package org.ielts.repository;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.ielts.domain.log.FirstRecordLog;
import org.ielts.domain.query.VisitorQuery;
import org.ielts.domain.security.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.yifeng.dao.HibernateRepository;
import com.yifeng.page.table.Paginations;

@Repository
public class FirstRecordLogRepository extends HibernateRepository<FirstRecordLog, String> {

	public Page<FirstRecordLog> findAll(VisitorQuery query, Pageable pageable) {
		DetachedCriteria criteria = createDetachedCriteria();

		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

		if (query.hasCreator()) {
			criteria.createCriteria("creator").add(Restrictions.eq("id", query.getCreator()));
		}
		if (query.hasTimePair()) {
			criteria.add(Restrictions.between("logTime", query.getTimePair().getStartDate(), query.getTimePair()
					.getEndDate()));
		}
		if (query.hasCampus()) {
			criteria.createCriteria("campus").add(Restrictions.eq("id", query.getCampusId()));
		}

		DetachedCriteria studentCriteria = null;
		if (query.hasName()) {
			studentCriteria = criteria.createCriteria("student");
			studentCriteria.add(Restrictions.like("name", query.getName(), MatchMode.ANYWHERE));
		}
		if (query.hasNumber()) {
			if (studentCriteria == null) {
				studentCriteria = criteria.createCriteria("student");
			}
			studentCriteria.add(Restrictions.or(Restrictions.like("phone", query.getNumber(), MatchMode.START),
					Restrictions.like("mobile", query.getNumber(), MatchMode.START)));
		}

		criteria.addOrder(Order.desc("logTime"));

		@SuppressWarnings("unchecked")
		List<FirstRecordLog> users = hibernateTemplate.findByCriteria(criteria, pageable.getOffset(),
				pageable.getPageSize());

		long total = firstLongQuery(criteria);

		return new PageImpl<FirstRecordLog>(users, pageable, total);
	}
}
